package pers.cz.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import pers.cz.model.SystemPartitionConstParam;

import javax.annotation.PostConstruct;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.Map;

/**
 * 分表规则加载计算,该类要在MyBatis Mapper文件加载之后加载
 * @program: PostGirl-panent
 * @description: PartitionUtil
 * @author: Cheng Zhi
 * @create: 2022-04-20 20:32
 **/
@Service
@Lazy  // 延迟加载 使用的时候再加载，todo 由于分表后分页查询的问题没有得到解决，所以暂时不进行分表
public class PartitionUtil {

    Logger logger = LoggerFactory.getLogger(PartitionUtil.class);
    private PartitionContext engine;
    private Map<String, SystemPartitionConstParam> constsContext;

    /**
     * 初始化分表规则
     */
    @PostConstruct
    public void initPartitionConfig() throws ScriptException, IOException {

        PartitionContextBuilder builder =new PartitionContextBuilder();
        engine = builder.build();
        constsContext = builder.getConsts();
        if(engine==null){
            logger.warn("The Lua Post-gril partition strategy load failure, will not take effect.");
        }else{
            logger.info("分表规则加载成功");
        }

    }

    /**
     * 获取参数集合
     * @return
     */
    public Map<String, SystemPartitionConstParam> getConstsContext() {
        return constsContext;
    }

    public String getTableName(String baseName, Map<String, Object[]> params, String expectStr) {
        String eval = null;
        try {
            logger.debug("开始计算表名..." + baseName);
            eval = engine.eval(baseName, params, null);
        } catch (Exception e) {
            logger.error("load rules fail...", e);
        }

        return eval;
    }
}
